//
//  NSDate+CompareDate.m
//  判断时间
//
//  Created by dllo on 16/9/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NSDate+CompareDate.h"

@implementation NSDate (CompareDate)

- (int)compareOtherDate:(NSDate *)otherDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *selfString = [dateFormatter stringFromDate:self];
    NSString *otherString = [dateFormatter stringFromDate:otherDate];
    NSDate *selfDate = [dateFormatter dateFromString:selfString];
    NSDate *anotherDate = [dateFormatter dateFromString:otherString];
    NSComparisonResult result = [selfDate compare:anotherDate];
    return result;
}

- (int)compareOtherDateString:(NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *otherDate = [dateFormatter dateFromString:dateString];
    return [self compareOtherDate:otherDate];
}

+ (NSString *)intervalStringFromDate:(NSDate *)date {
    NSTimeInterval interval = ceil([[NSDate date] timeIntervalSinceDate:date]);

    const NSInteger fiveMinuteSecond = 5 * 60;
    const NSInteger minuteSecond = 60;
    const NSInteger hourSecond = 60 * minuteSecond;
    const NSInteger daySecond = 24 * hourSecond;
    const NSInteger weekSecond = 7 * daySecond;
    const NSInteger monthSecond = 30 * daySecond;
    
    if (interval >= monthSecond) {
        return [NSString stringWithFormat:@"%.f 月 前", round(interval / monthSecond)];
    } else if (interval >= weekSecond) {
        return [NSString stringWithFormat:@"%.f 周 前", interval / weekSecond];
    } else if (interval >= daySecond) {
        return [NSString stringWithFormat:@"%.f 天 前", interval / daySecond];
    } else if (interval >= hourSecond) {
        return [NSString stringWithFormat:@"%.f 小时 前", interval / hourSecond];
    } else if (interval >= fiveMinuteSecond) {
        return [NSString stringWithFormat:@"%.f 分钟 前", interval / minuteSecond];
    } else if (interval < fiveMinuteSecond) {
        return @"片刻之前";
    } else {
        return nil;
    }
}

+ (NSString *)intervalStringFromDateString:(NSString *)dateString {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [df dateFromString:dateString];
    return [NSDate intervalStringFromDate:date];
}

@end
